package com.jpa.service;

import com.jpa.entity.User;
import com.jpa.repository.UserRepository;
import org.hibernate.mapping.Map;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zqf
 * @Date 2023/6/9 16:52
 * @Description:
 */
@Service
public class UserService {

    @Resource
    private UserRepository userRepository;


    /**
     * 主键查询
     *
     * @param id
     * @return
     */
    public User findById(Integer id) {
        return userRepository.getOne(id);
    }

    /**
     * 无条件的分页
     *
     * @return
     */
    public Page<User> findByNoCondition() {
        Pageable pageRequest = PageRequest.of(1, 10, Sort.Direction.DESC);
        return userRepository.findAll(pageRequest);
    }


    /**
     * 主键删除
     *
     * @param id
     * @return
     */
    public void delById(Integer id) {
        userRepository.deleteById(id);
    }


    /**
     * 新增和修改，注意：有id是修改，无id是新增
     *
     * @param id
     * @return
     */
    public void save(Integer id) {
        User user = userRepository.save(new User());
    }


    /**
     * 批量新增和修改，注意：有id是修改，无id是新增
     *
     * @param id
     * @return
     */
    public void saveList(Integer id) {
        ArrayList<User> users = new ArrayList<>();
        userRepository.saveAll(users);
    }


    /**
     * 带条件的分页（单表）
     *
     * @return
     */
    public Page<User> findByCondition(String name, Integer age) {
        Pageable pageRequest = PageRequest.of(1, 10, Sort.Direction.DESC);
        return userRepository.findAll((Specification<User>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            if (StringUtils.hasText(name)) {
                list.add(criteriaBuilder.equal(root.get("name").as(String.class), name));
            }
            if (null != age) {
                list.add(criteriaBuilder.le(root.get("age").as(Integer.class), age));
            }
            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        },pageRequest);
    }
}
